<template>
  <div>
    <a-form :form="form" class="form">
      <a-card
        :bordered="false"
        title="必填信息"
        :loading="loading1 || loading3"
      >
        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item
              label="用户名(登录账号)"
              has-feedback
              :validate-status="rules.userName.status"
              :help="rules.userName.help"
            >
              <a-input
                @blur="checkUserName('userName')"
                placeholder="请输入用户名"
                v-decorator="['userName',{rules: [
                      {
                        required: true,
                        message: '请输入昵称',
                      }],initialValue: formData.userName }]"
              />
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="密码(登录密码)">
              <a-input
               v-if="resetPassWord"
                type="password"
                placeholder="请输入密码"
                v-decorator="[
                  'passWord',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                      },
                      { validator: checkPassWord },
                      { min: 6, message: '不得少于6个字符' },
                      { max: 20, message: '不得超过20个字符' },
                    ],
                  },
                ]"
              />
              <a-button type="primary" @click="resetPassWord = true"  v-show="!resetPassWord">重置</a-button>
              <a-button type="primary" @click="resetPassWord = false"  v-show="resetPassWord">取消重置</a-button>
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="昵称">
              <a-input
                placeholder="请输入昵称"
                v-decorator="[
                  'nickName',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入昵称',
                      },
                      { max: 255, message: '不得超过255个字符' },
                    ],
                    initialValue: formData.nickName,
                  },
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row class="form-row">
        

          <a-col :lg="{ span: 7  }" :sm="24">
            <a-form-item label="真实姓名">
              <a-input
                placeholder="请输入真实姓名"
                v-decorator="[
                  'realName',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入真实姓名',
                      },
                      { max: 255, message: '不得超过255个字符' },
                    ],
                    initialValue: formData.realName,
                  },
                ]"
              />
            </a-form-item>
          </a-col>
  <a-col :lg="{ span: 7,offset: 1}" :sm="24">
            <a-form-item label="选择权限">
              <a-select
                :showSearch="true"
                optionFilterProp="label"
                placeholder="请选择权限"
                v-decorator="[
                  'roleId',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请选择权限',
                      },
                    ],
                    initialValue: Number(formData.roleId),
                  },
                ]"
              >
                <a-select-option
                  :value="item.id"
                  v-for="(item, index) in adminRoleList"
                  :key="index"
                  :label="item.name"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="状态">
              <a-switch
                checked-children="启用"
                un-checked-children="禁用"
                  v-decorator="['status',  { valuePropName: 'checked',initialValue: formData.status ==1 ?true:false } ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
 <a-card
        class="card"
        :title="'CRM系统'"
        :bordered="false"
        :loading="treeDataLoading || crmRoleList.loading"
        style="margin-top: 20px"
      >
      
      <a-row class="form-row">
            <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item label="所属部门">
              <a-tree-select
                show-search
                style="width: 100%"
                :treeData="treeData"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                treeNodeFilterProp='title'
                placeholder="请选择所属部门"
                allow-clear
                tree-default-expand-all
                :replaceFields="{
                   title:'name',
                   key:'id',
                   value:'id'
                }"
                  v-decorator="[
                  'division_id',
                  {
                    initialValue:formData.division_id?Number(formData.division_id):undefined
                  },
                ]"
              >
                <!-- <a-icon slot="suffixIcon" type="smile" /> -->
              </a-tree-select>
            </a-form-item>
          </a-col>


          <!-- <a-col :lg="{ span: 7,offset:1 }" :sm="24">
            <a-form-item label="选择CRM权限">
              <a-select
                :showSearch="true"
                optionFilterProp="label"
                allowClear
                placeholder="请选择CRM权限"
                v-decorator="[
                  'crm_role_id',
                  {
                    initialValue:formData.crm_role_id ? Number(formData.crm_role_id) : undefined,
                  },
                ]"
              >
                <a-select-option
                  :value="item.id"
                  v-for="(item, index) in crmRoleList.data"
                  :key="index"
                  :label="item.name"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
        </a-row>
      
      
      </a-card>
      <a-card
        class="card"
        :title="'选填信息'"
        :bordered="false"
        style="margin-top: 20px"
        :loading="loading1 || loading3"
      >
        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item label="电话">
              <a-input
                placeholder="请输入电话"
                v-decorator="[
                  'phone',
                  {
                    rules: [
                      { max: 255, message: '不得超过255个字符' },
                      { validator: checkPhone },
                    ],
                    initialValue: formData.phone,
                  },
                ]"
              />
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="邮箱">
              <a-input
                placeholder="请输入邮箱"
                v-decorator="[
                  'email',
                  {
                    rules: [
                      { max: 255, message: '不得超过255个字符' },
                      { type: 'email', message: '必须为邮箱格式' },
                    ],
                    initialValue: formData.email,
                  },
                ]"
              />
            </a-form-item>
          </a-col>
         
          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="生日">
              <a-date-picker
                style="width: 100%"
                placeholder="请选择日期"
                v-decorator="[
                  'birthday',
                  {
                    rules: [],
                    initialValue:formData.birthday?moment(formData.birthday, 'YYYY-MM-DD'):'',
                  },
                ]"
              />

              <!-- <a-input
                placeholder="请选择日期"
                type="date"
                v-decorator="[
                  'birthday',
                  {
                    initialValue: formData.birthday,
                  },
                ]"
              /> -->
            </a-form-item>
          </a-col>
        </a-row>

        <a-row class="form-row">
          <a-col :lg="{ span: 7 }" :sm="24">
            <a-form-item label="头像">
              <!-- <div class="portraitShow" @click="setPortrait()">
                <a-icon class="plus-icon" type="plus" v-show="!readerResult" />

                <input
                  type="file"
                  id="portrait"
                  style="display: none"
                  title=""
                  @change="portraitChange"
                />
                <div class="portraitImage" v-show="readerResult">
                  <img style="width: 100%; height: 100%" :src="readerResult" />
                </div>
              </div> -->
              <OneImage ref="oneImage" :imageUrl="formData.avatar?imageUrl(formData.avatar):''"/>
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="性别">
              <a-radio-group
                name="sex"
                v-decorator="[
                  'sex',
                  {
                    rules: [],
                    initialValue: formData.sex,
                  },
                ]"
              >
                <a-radio :value="`男`"> 男 </a-radio>
                <a-radio :value="`女`"> 女 </a-radio>
                <a-radio :value="`未知`"> 未知 </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>

          <a-col :lg="{ span: 7, offset: 1 }" :sm="24">
            <a-form-item label="详细地址">
              <a-input
                type="textarea"
                v-decorator="['belongs', {
                    initialValue: formData.belongs,

                }]"
                placeholder="详细地址"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <footer-tool-bar>
        <a-button type="primary" @click="validate" :loading="loading2"
          >提交</a-button
        >
      </footer-tool-bar>
    </a-form>
  </div>
</template>

<script>
import {
  adminRoleList,
  adminSelOne,
  adminEdit,
  adminAvatar,
} from "@/services/admin";
import FooterToolBar from "@/components/tool/FooterToolBar";
import moment from 'moment'//导入文件
import OneImage from "@/components/uploadImages/oneImage"
import {divisionList}   from "@/services/division"
// import { crmRoleSelectList } from "@/services/crmRole"


export default {
  name: "AdminAdd",
  //   i18n: require('../i18n'),
  components: {
    // CollectionCreateForm: CollectionCreateForm,
    FooterToolBar,
    OneImage
    // FormEdit: FormEdit,
  },
  data() {
    return {
      //   phoneMessageColumns: phoneMessageColumns,
      //   annalsPhoneColumn: annalsPhoneColumn,
      //   annalsEmailColumn: annalsEmailColumn,
      // phoneMessage: [],
      // dataSource:dataSource,
      // columns:columns,
      //   groupList: [],
      form: this.$form.createForm(this),
      // fileData: new FormData(),
      moment:moment,
      formData: {
        birthday:''
      },
      //   visible: false,
      resetPassWord:false,
       treeData:  [
       
      ],
      adminRoleList: [],
      rules: {
        userName: {
          status: "",
          help: "",
        },
      },
      // checkUserNameRepeat: checkUserNameRepeat,
      readerResult: "",
      loading1: false, //下拉
      loading2: false, //提交
      loading3: false, //查单条
      treeDataLoading:false,
      crmRoleList:{
        data:[],
        loading:false,
      },
      keys: 0,
      title: "",
      id: "",
    };
  },
  created() {
    // this.closeTabs.$emit('test','msg');
    this.id = this.$route.query.admin_id;
    // console.log(this.form)
    // moment().format('MMMM Do YYYY, h:mm:ss a'); 
    // console.log(moment().format('MMMM Do YYYY, h:mm:ss a'))
  },
  watch: {
    "$route.query.admin_id": function () {
      let admin_id = this.$route.query.admin_id;
      if (admin_id && admin_id != this.id) {
        this.id = admin_id;
      }
      //重新调用请求数据的方法，刷新页面数据
    },
    id(newValue, oldValue) {
      this.loading3 = true;
      adminSelOne({ id: newValue })
        .then((res) => {
          if (res.code == 200) {
            this.formData = res.data;
            this.readerResult = this.formData.avatar
            console.log(this.formData.userName)
            this.divisionListLoad()
            // this.crmRoleSelectListLoad()
            this.adminRoleListLoad(this.formData.roleId);
            this.loading3 = false;
          }
        })
    },
  },
  methods: {
      async divisionListLoad(){
      this.treeDataLoading = true

        let res =    await divisionList({keyWord:{'equal-crm_division-status':1}})
        if(res.code == 200){

           this.treeData = res.data.list 
        }
      this.treeDataLoading = false

    },
    // async crmRoleSelectListLoad(){
    //      this.crmRoleList.loading = true
    //      let res =  await crmRoleSelectList()
    //      if(res.code == 200){
    //         const {list} = res.data 
    //         this.crmRoleList.data = list
    //      }
    //      this.crmRoleList.data.unshift({'id':0,'name':'超级管理员(拥有所有权限)'})

    //      this.crmRoleList.loading = false
    // },
    async validate() {
      // alert()

      //  let
      // console.log();
      //   console.log(tree.checkedKeys);
      const { form, $message, $router, $refs,rules, fmtDate,id } = this;
      let this_ = this;

       this.checkUserName("userName");

      form.validateFields((err) => {
        if (err || rules.userName.status != "success") {
          $message.error("信息填写有误");
          return;
        } else {
          // console.log(form.getFieldsValue());
          this.$confirm({
            title: "确定要编辑吗?",
            // content: h => <div style="color:red;">Some descriptions</div>,
            async onOk() {
              this_.loading2 = true;
              // if()
              let formData = form.getFieldsValue();
              let fileData = $refs.oneImage.getFile()
              if (fileData.has("file")) {
                console.log(fileData.get("file"))
                 if (!fileData.get("file")) {
                  formData["avatar"] = "";
                } else {
                let fileRes = await adminAvatar(fileData);
                if (fileRes.code == 200) {
                  formData["avatar"] = fileRes.data.url;
                } else {
                  return;
                }
                }
              }
              if (formData["birthday"]) formData["birthday"] = fmtDate(formData["birthday"])
              if(!formData['division_id'])formData['division_id'] = null
              let res = await adminEdit({ formData,id });
              if (res.code == 200) {
                $message.success(res.message);
                this_.closeTabs.$emit("closeTabs");
                $router.push("/personnelManagement/adminList");
              } else if (res.code == 100 && res.message == "该用户名已存在") {
                rules["userName"].status = "error";
                rules["userName"].help = res.message;
              }

              // console.log(formData);

              this_.loading2 = false;
            },
          });
        }
      });
    },

    adminRoleListLoad(roleId) {
      // return new Promise((resolve, reject) => {
        this.loading1 = true;
        adminRoleList({ selectOrId: roleId, field: ["id", "name"] }).then(
          (res) => {
            if (res.code == 200) {
              this.adminRoleList = res.data;
            } 
            this.adminRoleList.unshift({"id":-1,"name":"无权限"})

            // this.adminRoleList.unshift({ id: 0, name: "超级管理员(拥有所有权限)" });
            this.loading1 = false;
          }
        );
      // });

      //   })
    },
     checkUserName(key) {
      this.rules[key].status = "validating";
      let field = this.form.getFieldValue(key);
      if (!field || field.trim() == "") {
        this.rules[key].status = "error";
        this.rules[key].help = "请输入用户名";
        return;
      } else if (field.length < 5) {
        this.rules[key].status = "error";
        this.rules[key].help = "不得少于5个字符";
        return;
      } else if (new RegExp("[^\\w]").test(field)) {
        this.rules[key].status = "error";
        this.rules[key].help = "用户名只能由字母数字下划线组成";
        return;
      } else if (field.length > 20) {
        this.rules[key].status = "error";
        this.rules[key].help = "不得超过20个字符";
        return;
      }
      this.rules[key].status = "success";
      this.rules[key].help = "";
    },
   
  },
};
</script>

<style scoped lang="less">
.aSelect {
  display: flex;
  width: 100%;
  justify-content: space-between;
  /* border: 1px solid red; */
  align-items: center;
}

.card {
  margin-bottom: 24px;
}

.form {
  .form-row {
    margin: 0 -8px;
    // display: flex;
    // justify-content: space-between;
    //    display: flex;
    // justify-content: space-between;
  }
  .ant-col-md-12,
  .ant-col-sm-24,
  .ant-col-lg-6,
  .ant-col-lg-8,
  .ant-col-lg-10,
  .ant-col-xl-8,
  .ant-col-xl-6 {
    padding: 0 8px;
  }
}
.topRow button {
  margin-top: 5px;
  margin-left: 10px;
}

.portraitImage {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  //   border: 1px solid red;
}

#portraitImage {
  //   width: 100%;
  //   height: 100%;
}

.portraitShow {
  width: 70%;
  height: 0;
  padding-bottom: 70%;
  border: 1px dashed #ced0d3;
  // margin-left: 20px;
  position: relative;
  margin: auto;
  // display: flex;
  // justify-content: center;
  // align-items: center;
  cursor: pointer;
}
.plus-icon {
  position: absolute;
  left: 50%;
  top: 50%;
  font-size: 20px;
  transform: translate(-50%, -50%); /* 50%为自身尺寸的一半 */
}
</style>
